package xt.outfood.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.similarities.Lambda;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.stylesheets.LinkStyle;
import xt.outfood.common.Result;
import xt.outfood.dto.DishDto;
import xt.outfood.entity.Category;
import xt.outfood.entity.Dish;
import xt.outfood.entity.DishFlavor;
import xt.outfood.service.CategoryService;
import xt.outfood.service.DishFlavorService;
import xt.outfood.service.DishService;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理和口味管理都放在里面
 *
 * @author 小小爱欧
 * @date 2022/7/26 10:56
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    //加入缓存机制
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品，需要操作Dish和DishFlavor两个表，但传过来的对象不满足，需要在封装成dto进行转换。
     * DTO:数据传输对象，一般用于展示层与服务层之间的数据传输
     * 使用@RequestBody接收前端传过来的json数据。
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return Result.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件
        queryWrapper.eq(name != null, Dish::getName, name);

        //  执行分页查询
        dishService.page(dishPage, queryWrapper);

        //  将 dish 中的属性值复制到 dtoPage，但是忽略 records
        //  records需要另外去设置
        BeanUtils.copyProperties(dishPage, dtoPage, "records");

        List<Dish> records = dishPage.getRecords();
        List<DishDto> dtoList = records.stream().map((dish) -> {  // dish 为每个菜品对象
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(dish, dishDto);

            Long categoryId = dish.getCategoryId();  // 菜品的分类id

            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }

            return dishDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(dtoList);
        return Result.success(dtoPage);
    }

    /**
     * 根据id查询菜品信息和口味信息
     *
     * @param id
     * @return
     */
//    @CachePut(value="dishDto",key = "#id")
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id) {
        //查询两张表
        DishDto dishDto = dishService.getByIdWithFlavor(id);
//        log.info("缓存数据。。。。。。。。。。。。{}");
        return Result.success(dishDto);
    }

//    @CacheEvict(value = "del", key = "#dishDto")
    @PutMapping()
    public Result<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //清理所有菜品的缓存数据
        //得到所有的以disj开头的所有的key
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        //精确清理某个菜品的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        log.info("清除缓存数据》》》{}}");
        redisTemplate.delete(key);
        return Result.success("修改菜品成功");
    }

    /**
     * 通过条件查询对应的菜品数据
     *
     * @param dish
     * @return
     */
    @Cacheable(value = "listCache", key = "#dish")
    @GetMapping("/list")
    public Result<List<DishDto>> list(Dish dish) {
        /**
         * 先从redis中获取缓存数据
         * 存在则直接返回，无需查询数据库
         * 不存在则查询数据库，将查询到的菜品数据缓存到redis中
         * 缓存中的key为动态构造
         */
        List<DishDto> dishDtoList = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            //缓存中存在则直接返回数据
            log.info("缓存中有数据，直接返回数据->>>,{}", dishDtoList);
            Result.success(dishDtoList);
        }
        //缓存中不存在则查询数据库如下
        //先构造查询条件，然后再执行查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //eq相当于where
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加查询条件，只查询状态值为1的
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        dishDtoList = list.stream().map(
                (item) -> {
                    DishDto dishDto = new DishDto();
                    BeanUtils.copyProperties(item, dishDto);
                    Long categoryId = item.getCategoryId();
                    Category category = categoryService.getById(categoryId);
                    if (category != null) {
                        dishDto.setCategoryName(category.getName());
                    }
                    //当前菜品的id,根据dishId去查询当前菜品对应的口味
                    Long dishId = item.getId();
                    LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    flavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
                    //select * from dish_flavor where id=?
                    List<DishFlavor> dishFlavors = dishFlavorService.list(flavorLambdaQueryWrapper);
                    dishDto.setFlavors(dishFlavors);
                    return dishDto;
                }
        ).collect(Collectors.toList());
        //查询之后存入redis中60分钟
        log.info("无缓存，直接查数据库:", dishDtoList);
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return Result.success(dishDtoList);

    }

}
